package com.limuzi.config;

import com.limuzi.util.DingTalkSendMsgUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.ServletRequest;
import java.nio.charset.Charset;
import java.util.Objects;

/**
 * @author: limuzi
 * @create: 2023-06-26
 */
@Slf4j
@RestControllerAdvice
public class GlobalException {

    @ExceptionHandler(Exception.class)
    public String exceptionHandler(Exception e, ServletRequest request){
        if(Objects.isNull(request) && request instanceof ContentCachingRequestWrapper){
            ContentCachingRequestWrapper wrapper =(ContentCachingRequestWrapper) request;
            log.info("未知异常 request ip: {}, url: {}, body: {}", wrapper.getRemoteAddr(),
                    wrapper.getRequestURI(), StringUtils.toEncodedString(wrapper.getContentAsByteArray(),
                            Charset.forName(wrapper.getCharacterEncoding())));
        }
        log.error("未知异常", e);
        DingTalkSendMsgUtils.sendToDingTalk(e);
        return "系统异常，请联系管理员";
    }
}
